import os
import platform
from typing import Dict, List, Optional, Any
from .cache_service import CacheService
import logging

logger = logging.getLogger(__name__)

class FileSystemService:
    def __init__(self):
        self.root_paths = self._get_root_paths()
        self.cache = CacheService(default_ttl=300)  # 5分钟缓存

    def _get_root_paths(self) -> List[str]:
        """获取系统根目录"""
        if platform.system() == "Windows":
            from ctypes import windll
            drives = []
            bitmask = windll.kernel32.GetLogicalDrives()
            for letter in range(65, 91):
                if bitmask & 1:
                    drives.append(chr(letter) + ":\\")
                bitmask >>= 1
            return drives
        return ["/"]  # Unix-like systems

    def _get_cache_key(self, path: str, max_depth: int) -> str:
        """生成缓存键"""
        return f"dir_tree:{path}:{max_depth}"

    def scan_directory(self, path: str, max_depth: int = 3) -> Dict:
        """扫描目录结构（带缓存）"""
        cache_key = self._get_cache_key(path, max_depth)
        cached_result = self.cache.get(cache_key)
        if cached_result is not None:
            return cached_result

        result = {
            "name": os.path.basename(path) or path,
            "path": path,
            "type": "directory",
            "children": []
        }
        
        try:
            if max_depth > 0:
                for item in os.listdir(path):
                    full_path = os.path.join(path, item)
                    if os.path.isdir(full_path):
                        result["children"].append(
                            self.scan_directory(full_path, max_depth - 1)
                        )
                    else:
                        result["children"].append({
                            "name": item,
                            "path": full_path,
                            "type": "file",
                            "size": os.path.getsize(full_path)
                        })
        except PermissionError:
            result["error"] = "访问权限被拒绝"
        except Exception as e:
            result["error"] = str(e)

        # 缓存结果
        self.cache.set(cache_key, result)
        return result

    def invalidate_cache(self, path: Optional[str] = None) -> None:
        """清除指定路径的缓存，如果path为None则清除所有缓存"""
        if path is None:
            self.cache.clear()
        else:
            # 清除与该路径相关的所有缓存
            for depth in range(10):  # 假设最大深度为10
                cache_key = self._get_cache_key(path, depth)
                self.cache.delete(cache_key)



def read_file_content(file_path: str, encoding: str = 'utf-8') -> Optional[Dict[str, Any]]:
    """
    读取指定文件内容
    
    Args:
        file_path: 文件路径
        encoding: 文件编码，默认utf-8
        
    Returns:
        Dict: 包含文件内容的字典，如果是文本文件则包含元数据
        None: 如果文件不存在或读取失败
    """
    try:
        if not os.path.exists(file_path):
            logger.error(f"文件不存在: {file_path}")
            return None
            
        file_ext = os.path.splitext(file_path)[1].lower()
        
        # 如果是文本文件
        if file_ext == '.txt':
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
                
            # 解析元数据
            metadata = {}
            lines = content.split('\n')
            content_start = 0
            
            for i, line in enumerate(lines):
                if not line.strip():  # 遇到空行表示元数据部分结束
                    content_start = i + 1
                    break
                    
                if ':' in line:
                    key, value = line.split(':', 1)
                    metadata[key.strip()] = value.strip()
            
            return {
                'type': 'text',
                'metadata': metadata,
                'content': '\n'.join(lines[content_start:])
            }
            
        # 如果是图片文件
        elif file_ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
            return {
                'type': 'image',
                'path': file_path,
                'size': os.path.getsize(file_path)
            }
            
        # 如果是视频文件
        elif file_ext in ['.mp4', '.avi', '.mov']:
            return {
                'type': 'video',
                'path': file_path,
                'size': os.path.getsize(file_path)
            }
            
        # 其他类型文件
        else:
            return {
                'type': 'unknown',
                'path': file_path,
                'size': os.path.getsize(file_path)
            }
            
    except Exception as e:
        logger.error(f"读取文件失败 {file_path}: {str(e)}")
        return None

def read_directory_content(directory: str) -> Optional[Dict[str, Any]]:
    """
    读取指定目录下的所有内容
    
    Args:
        directory: 目录路径
        
    Returns:
        Dict: 包含目录下所有文件内容的字典
        None: 如果目录不存在或读取失败
    """
    try:
        if not os.path.exists(directory):
            logger.error(f"目录不存在: {directory}")
            return None
            
        result = {
            'path': directory,
            'name': os.path.basename(directory),
            'files': []
        }
        
        # 读取目录下所有文件
        for file_name in os.listdir(directory):
            file_path = os.path.join(directory, file_name)
            if os.path.isfile(file_path):
                file_content = read_file_content(file_path)
                if file_content:
                    result['files'].append({
                        'name': file_name,
                        **file_content
                    })
        
        return result
        
    except Exception as e:
        logger.error(f"读取目录失败 {directory}: {str(e)}")
        return None
